package com.ruoyi.qywx.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.cache.Meta;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StrUtils;
import com.ruoyi.qywx.entity.QyPublicWelcome;
import com.ruoyi.qywx.entity.QyWelcomeTemplate;
import com.ruoyi.qywx.getway.entity.QyWelcome;
import com.ruoyi.qywx.getway.keys.QywxKey;
import com.ruoyi.qywx.mapper.PublicWelcomeMapper;
import com.ruoyi.qywx.service.inters.PublicWelcomeService;
import com.ruoyi.qywx.service.inters.WelcomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author : hcl
 * @Date : 2023/8/22 14:19
 */
@Service
public class PublicWelcomeServiceImpl implements PublicWelcomeService {
    @Resource
    private PublicWelcomeMapper publicWelcomeMapper;
    @Autowired
    private WelcomeService welcomeService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 需要检查
     */
    @Transactional
    @Override
    public AjaxResult insert(QyPublicWelcome publicWelcome) {
        return null;
    }

    @Transactional
    @Override
    public AjaxResult update(Long welcomeId, Long teamId) {
        return null;
    }

    @Override
    public List<QyPublicWelcome> selectByTeamId(Long welcomeId, Long teamId) {
        return null;
    }

    @Override
    public QyWelcome findPublicWelcomByUserId(String userId, Meta meta) {
        if (StrUtils.isEmpty(userId)) {
            return null;
        }
        String key = QywxKey.RedisKey.extContactPubWelcomeKey(meta.getTeamId(), userId);
        QyWelcome welcome = redisCache.getCacheObject(key);
        if (Objects.nonNull(welcome)) { // 兜底的欢迎语 流量不会太大
            redisCache.expire(key, 1, TimeUnit.MINUTES);
            return welcome;
        }
        QyPublicWelcome pubWelcome = publicWelcomeMapper.selectOne(new QueryWrapper<QyPublicWelcome>()
                .eq("team_id", meta.getTeamId())
                .apply("FIND_IN_SET({0},users)", userId));
        if (Objects.isNull(pubWelcome)) {
            return null;
        }
        QyWelcomeTemplate template = welcomeService.selectById(pubWelcome.getWelcomeId());
        QyWelcome qyWelcome = QyWelcome.of(template, null, null, meta);
        redisCache.setCacheObject(key, qyWelcome, 1, TimeUnit.MINUTES);
        return qyWelcome;
    }
}
